import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:xiongan_app_yy/common/user_singleton.dart';
import 'package:xiongan_app_yy/entrys/rp/car_info_list_entity.dart';
import 'package:xiongan_app_yy/entrys/rp/erp_odd_numbers_entity.dart';
import 'package:xiongan_app_yy/entrys/rp/inv_list_details_entity.dart';
import 'package:xiongan_app_yy/entrys/rp/inv_list_entity.dart';
import 'package:xiongan_app_yy/net/internet_api.dart';
import 'package:xiongan_app_yy/pages/common/LoadBuilder.dart';
import 'package:xiongan_app_yy/pages/common/car_info_list.dart';
import 'package:xiongan_app_yy/pages/common/car_number_page.dart';
import 'package:xiongan_app_yy/provider/erp_info.dart';
import 'package:xiongan_app_yy/utils/license_plate_utils.dart';
import 'package:xiongan_app_yy/utils/toast_utils.dart';
import 'package:xiongan_app_yy/widgets/comm/dropdown_card_widget.dart';
import 'package:xiongan_app_yy/widgets/comm/input_card_widget.dart';
import 'package:xiongan_app_yy/widgets/comm/input_card_widget_new.dart';
import 'package:xiongan_app_yy/widgets/comm/scan_widget.dart';
import 'package:xiongan_app_yy/widgets/comm/text_card_widget_new.dart';
import 'package:xiongan_app_yy/widgets/comm/time_card_widget.dart';
import 'package:xiongan_app_yy/widgets/inv_list_page_new_widget.dart';
import 'package:xiongan_app_yy/widgets/comm/left_icon_widget.dart';
import 'package:xiongan_app_yy/widgets/notification/erp_notification.dart';
import 'package:xiongan_app_yy/widgets/notification/image_notification.dart';
import 'package:xiongan_app_yy/widgets/notification/time_notification.dart';

//调配预约-新建
class DeploymentListPageNew extends StatefulWidget {
  final Map<String, dynamic> args;

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return DeploymentListPageNewState();
  }

  DeploymentListPageNew(this.args);
}

class DeploymentListPageNewState extends State<DeploymentListPageNew> {
  final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();
  bool visibility = true; //false不隐藏，true隐藏
  var _futureBuilderFuture;
  String time;
  List<String> imageList;
  List<File> imageFileList;
  int index;
  String data;
  String selectValue;
  String orgId;
  bool load = false;
  bool Use = true;
  String proText = "浙";
  double textNum = 0;
  ErpOddNumbersEntity bean;
  ErpOddNumbersEntity beanNew;
  ErpOddNumbersData detailsBean;
  List<String> numberList = new List();
  TextEditingController controller = TextEditingController();
  TextEditingController controller0 = TextEditingController();
  TextEditingController controller1 = TextEditingController();
  TextEditingController controller2 = TextEditingController();
  List<CarInfoListItem> datas = [];
  String projectname;
  String projectno;
  String suppliername;

  Future _gerData() async {
    print(DataSingleton().Data.id);
    var response = InternetAPI.getInstance()
        .dio
        .get("OMS/MiErpWarehouseInOrder/GetAllErpOrder", queryParameters: {
      'operaterUserId': DataSingleton().Data.id,
      'pageNo': -1
    });
    return response;
  }

  @override
  void initState() {
    super.initState();
    if (widget.args != null) {
      InvListDetailsEntity bean = widget.args["bean"];
      selectValue = bean.datas.erpno;
      controller.text = bean.datas.erpno;
      controller0.text = bean.datas.driver;
      controller1.text = bean.datas.phone;
      projectname = bean.datas.projectname;
      projectno = bean.datas.projectno;
      suppliername = bean.datas.supplyname;
      orgId = bean.datas.id;
      datas.addAll(bean.datas.carList);
    }
    _futureBuilderFuture = _gerData();
  }

  @override
  Widget build(BuildContext context) {
    return NotificationListener(
        onNotification: (notification) {
          print(notification.runtimeType);
          switch (notification.runtimeType) {
            case ErpNotification:
              index = notification.index;
              detailsBean = beanNew.datas.elementAt(index);
              Provider.of<ErpInfo>(context)
                  .setMode(bean.datas.elementAt(index));
              setState(() {
                visibility = false;
                selectValue = notification.msg;
              });
              break;
            case TimeNotification:
              time = notification.msg;
              break;
            case ImageNotification:
              if (notification.msg == "String") {
                imageList = notification.list;
                print("图片list$imageList");
              } else {
                imageFileList = notification.fileList;
                print("图片file$imageFileList");
              }

              break;
          }
          return false;
        },
        child: Scaffold(
            key: scaffoldKey,
            appBar: AppBar(
              leading: LeftIconWidget(icon: Icons.chevron_left, isize: 36),
              title: Text(
                "新建调配预约",
                style: TextStyle(fontSize: 18),
              ),
              elevation: 0,
              centerTitle: true,
              backgroundColor: Color(0XFF00A5F1),
            ),
            body: FutureBuilder(
              builder: _buildFuture,
              future: _futureBuilderFuture,
            )));
  }

  ///snapshot就是_calculation在时间轴上执行过程的状态快照
  Widget _buildFuture(BuildContext context, AsyncSnapshot snapshot) {
    switch (snapshot.connectionState) {
      case ConnectionState.none:
        print('还没有开始网络请求');
        return Text('还没有开始网络请求');
      case ConnectionState.active:
        print('active');
        return Text('ConnectionState.active');
      case ConnectionState.waiting:
        print('waiting');
        return Center(
          child: CircularProgressIndicator(),
        );
      case ConnectionState.done:
        print('done');
        if (snapshot.hasError) {
          return Text('Error: ${snapshot.error}');
        }
        return _createListView(context, snapshot);
      default:
        return null;
    }
  }

  Widget _createListView(BuildContext context, AsyncSnapshot snapshot) {
    data = snapshot.data.toString();
    Map<String, dynamic> dataMap = jsonDecode(data);
    bean = new ErpOddNumbersEntity.fromJson(dataMap);
    beanNew = new ErpOddNumbersEntity.fromJson(dataMap);
    if (numberList.length == 0) {
      //这个判断是因为FutureBuilder在改变时会反复刷新执行builder（可能是键盘弹起造成的），会造成数据添加错乱。数据只添加一次
      bean.datas.forEach((erpOddNumbersData) {
        numberList.add(erpOddNumbersData.erpno);
      });
    }
    if (widget.args != null) {
      for (int i = 0; i < numberList.length; i++) {
        if (selectValue == numberList.elementAt(i).toString()) {
          Provider.of<ErpInfo>(context).setMode(bean.datas.elementAt(i));
          visibility = false;
          Use = false;
        }
      }
      if (Use == true) {
        selectValue = null;
      }
    }
    textNum = 0;
    if (Provider.of<ErpInfo>(context).mode != null) {
      for (int i1 = 0;
          i1 < Provider.of<ErpInfo>(context).mode.details.length;
          i1++) {
        textNum = Provider.of<ErpInfo>(context).mode.details[i1].qty + textNum;
      }
    }
    return LoadBuilder(
        bgColor: Colors.black26,
        visibility: load,
        builder: Column(
          children: <Widget>[
            Expanded(
                child: ListView(
              children: <Widget>[
                UploadImgWidget(),
                Column(
                  children: <Widget>[
                    Offstage(),
//                    DropdownCardWidget(
//                      hintText: "请选择发货通知单号",
//                      title: "发货通知单号:",
//                      data: numberList,
//                      selectValue: selectValue,
//                    ),
                    InputCardWidgetNew(
                      suffixIcon: ScanWidget(
                        clickCallback: (value) {
                          controller.text = value.trim();
                          matchErpInfo(value.trim());
                        },
                      ),
                      enabled: true,
                      hintText: "请输入调配单号",
                      title: "调配单号:",
                      contro: controller,
                      onChange: () {
                        if (controller.text.length == 10) {
                          matchErpInfo(controller.text);
                        }
                      },
                      enterListen: (value) {
                        if (value.length > 0) {
                          setState(() {
                            matchErpInfo(controller.text);
                          });
                        }
                      },
                      textAction: TextInputAction.done,
                    ),
                    TextCardWidgetNew(
                        onPressed: () {
                          //Navigator.pushNamed(context, "/storageDetails",arguments: detailsBean);
                          Navigator.pushNamed(context, "/carSelect",
                              arguments: {"datas": datas}).then((value) {
                            if (value != null) {
                              setState(() {
                                datas = value;
                              });
                            }
                          });
                        },
                        title: "车辆信息:",
                        textNum: false,
                        details: false,
                        num: "${datas.length}辆",
                        border: Border.fromBorderSide(BorderSide.none)),
//                    InputCardWidget(
//                      hintText: "请输入司机姓名",
//                      title: "司机姓名:",
//                      contro: controller0,
//                    ),
//                    InputCardWidget(
//                      hintText: "请输入司机手机号",
//                      title: "司机手机号:",
//                      contro: controller1,
//                      inputFormatters: [
//                        WhitelistingTextInputFormatter(RegExp("[0-9]")),
//                        LengthLimitingTextInputFormatter(11),
//                      ],
//                    ),
//                    CarNumberPage(true, controller2, proText,
//                        (proText) => _changeText(proText)),
                    Offstage(
                        offstage: visibility,
                        child: TextCardWidgetNew(
                            onPressed: () {
                              //Navigator.pushNamed(context, "/storageDetails",arguments: detailsBean);
                              Navigator.pushNamed(context, "/storageDetails",
                                  arguments: {
                                    "type": "push",
                                    "title": "调配物资明细",
                                    "data": detailsBean,
                                    "show": true,
                                  });
                            },
                            textNum: false,
                            num: textNum.toString(),
                            title: "物资明细:",
                            border: Border.fromBorderSide(BorderSide.none))),
                    TimeCardWidget(
                        scaffoldKey: scaffoldKey,
                        custom: true,
                        hintText: "请选择预约时间",
                        title: "预约时间:",
                        margin: EdgeInsets.only(top: 20),
                        border: Border.fromBorderSide(BorderSide.none)),
                  ],
                ),
              ],
            )),
            Container(
              width: double.infinity,
              height: 48,
              child: FlatButton(
                color: Color(0XFF00A5F1),
                child: Text(
                  "提交",
                  style: TextStyle(color: Colors.white),
                ),
                onPressed: upData,
              ),
            )
          ],
        ));
  }

  void upData() {
    if (selectValue != null && selectValue.length > 0) {
      for (int i = 0; i < datas.length; i++) {
        if (datas[i].driver != null && datas[i].driver.length > 0) {
          if (datas[i].phone != null && datas[i].phone.length > 0) {
            if (datas[i].carno != null &&
                datas[i].carno.length > 0 &&
                LicensePlateUtils.isLicensePlate(datas[i].carno)) {
              if (i + 1 == datas.length) {
                if (textNum != 0) {
                  if (time != null) {
                    setState(() {
                      load = true;
                    });
                    if (imageList == null && imageFileList == null) {
                      //没有图
                      List<ErpOddNumbersDatasDetail> data = [];
                      for (int i = 0;
                          i < Provider.of<ErpInfo>(context).mode.details.length;
                          i++) {
                        if (Provider.of<ErpInfo>(context)
                                .mode
                                .details
                                .elementAt(i)
                                .qty !=
                            0) {
                          data.add(Provider.of<ErpInfo>(context)
                              .mode
                              .details
                              .elementAt(i));
                        }
                      }
                      InternetAPI.getInstance().post(
                        "OMS/MiAllocationTaskDetail/AddMiAllocationTaskDetail",
                        (data) {
                          print(data.toString());
                          //Navigator.popAndPushNamed(context, "/success",result: "wu");
                          if (data == true) {
                            Navigator.pop(context, "ok");
                            TostUtil.showToast("提交成功");
                          }
                        },
                        errorCallBack: (err) {
                          setState(() {
                            load = false;
                          });
                        },
                        params: {
                          "operaterUserName": DataSingleton().Data.username,
                          "operaterUserId": DataSingleton().Data.id,
                          "tenantId": DataSingleton().Data.tenantId,
                          "creationTime":
                              DateTime.now().toString().substring(0, 19),
                          "carno": proText + controller2.text,
                          "applytime": time,
                          "erpno": selectValue,
                          "driver": controller0.text,
                          "phone": controller1.text,
                          "detailList": data,
                          "orgId": orgId,
                          "projectname": projectname != null
                              ? projectname
                              : detailsBean.details.elementAt(0).projectname,
                          "projectno": projectno != null
                              ? projectno
                              : detailsBean.details.elementAt(0).projectno,
                          "supplyname": suppliername != null
                              ? suppliername
                              : detailsBean.details.elementAt(0).suppliername,
                          "warehouseid": DataSingleton().warehouseChoice.id,
                          "appointmentmode": "20",
                          "department": data[0].department,
                          "carList": datas,
                          //"department": "雄安供电公司",
                        },
                      );
                    } else {
                      //有图
                      if (imageList.length == imageFileList.length) {
                        //图上传完成
                        List<ErpOddNumbersDatasDetail> data = [];
                        for (int i = 0;
                            i <
                                Provider.of<ErpInfo>(context)
                                    .mode
                                    .details
                                    .length;
                            i++) {
                          if (Provider.of<ErpInfo>(context)
                                  .mode
                                  .details
                                  .elementAt(i)
                                  .qty !=
                              0) {
                            data.add(Provider.of<ErpInfo>(context)
                                .mode
                                .details
                                .elementAt(i));
                          }
                        }
                        List<InvListDatasImglist> img = new List();
                        for (int i = 0; i < imageList.length; i++) {
                          img.add(InvListDatasImglist(
                              imgstr: imageList.elementAt(i)));
                        }
                        InternetAPI.getInstance().post(
                          "OMS/MiAllocationTaskDetail/AddMiAllocationTaskDetail",
                          (data) {
                            print(data.toString());
                            //Navigator.popAndPushNamed(context, "/success",result: "wu");
                            if (data == true) {
                              Navigator.pop(context, "ok");
                              TostUtil.showToast("提交成功");
                            }
                          },
                          errorCallBack: (err) {
                            setState(() {
                              load = false;
                            });
                          },
                          params: {
                            "operaterUserName": DataSingleton().Data.username,
                            "operaterUserId": DataSingleton().Data.id,
                            "tenantId": DataSingleton().Data.tenantId,
                            "creationTime":
                                DateTime.now().toString().substring(0, 19),
                            "carno": proText + controller2.text,
                            "applytime": time,
                            "erpno": selectValue,
                            "driver": controller0.text,
                            "phone": controller1.text,
                            "detailList": data,
                            "orgId": orgId,
                            "projectname": projectname != null
                                ? projectname
                                : detailsBean.details.elementAt(0).projectname,
                            "projectno": projectno != null
                                ? projectno
                                : detailsBean.details.elementAt(0).projectno,
                            "supplyname": suppliername != null
                                ? suppliername
                                : detailsBean.details.elementAt(0).suppliername,
                            "imgList": img,
                            "warehouseid": DataSingleton().warehouseChoice.id,
                            "appointmentmode": "20",
                            "department": data[0].department,
                            "carList": datas,
                            //"department": "雄安供电公司",
                          },
                        );
                      } else {
                        TostUtil.showToast("大图上传中，请稍后");
                      }
                    }
                  } else {
                    TostUtil.showToast("请选择预约时间");
                  }
                } else {
                  TostUtil.showToast("物资明细不能为0");
                }
              }
            } else {
              TostUtil.showToast("请填写第${i + 1}位正确的车牌号");
              break;
            }
          } else {
            TostUtil.showToast("请填写第${i + 1}位司机手机号");
            break;
          }
        } else {
          TostUtil.showToast("请填写第${i + 1}位司机姓名");
          break;
        }
      }
    } else {
      TostUtil.showToast("请输入正确的单号");
    }
  }

  void _upData() {
    if (selectValue != null && selectValue.length > 0) {
      if (controller0.text != null && controller0.text.length > 0) {
        if (controller1.text != null && controller1.text.length > 0) {
          if (controller2.text != null && controller2.text.length > 0) {
            if (LicensePlateUtils.isLicensePlate(proText + controller2.text)) {
              if (textNum != 0) {
                if (time != null) {
                  setState(() {
                    load = true;
                  });
                  if (imageList == null && imageFileList == null) {
                    //没有图
                    List<ErpOddNumbersDatasDetail> data = [];
                    for (int i = 0;
                        i < Provider.of<ErpInfo>(context).mode.details.length;
                        i++) {
                      if (Provider.of<ErpInfo>(context)
                              .mode
                              .details
                              .elementAt(i)
                              .qty !=
                          0) {
                        data.add(Provider.of<ErpInfo>(context)
                            .mode
                            .details
                            .elementAt(i));
                      }
                    }
                    InternetAPI.getInstance().post(
                      "OMS/MiAllocationTaskDetail/AddMiAllocationTaskDetail",
                      (data) {
                        print(data.toString());
                        //Navigator.popAndPushNamed(context, "/success",result: "wu");
                        if (data == true) {
                          Navigator.pop(context, "ok");
                          TostUtil.showToast("提交成功");
                        }
                      },
                      errorCallBack: (err) {
                        setState(() {
                          load = false;
                        });
                      },
                      params: {
                        "operaterUserName": DataSingleton().Data.username,
                        "operaterUserId": DataSingleton().Data.id,
                        "tenantId": DataSingleton().Data.tenantId,
                        "creationTime":
                            DateTime.now().toString().substring(0, 19),
                        "carno": proText + controller2.text,
                        "applytime": time,
                        "erpno": selectValue,
                        "driver": controller0.text,
                        "phone": controller1.text,
                        "detailList": data,
                        "orgId": orgId,
                        "projectname":
                            detailsBean.details.elementAt(0).projectname,
                        "projectno": detailsBean.details.elementAt(0).projectno,
                        "supplyname":
                            detailsBean.details.elementAt(0).suppliername,
                        "warehouseid": DataSingleton().warehouseChoice.id,
                        "appointmentmode": "20",
                        "department": data[0].department,
                        //"department": "雄安供电公司",
                      },
                    );
                  } else {
                    //有图
                    if (imageList.length == imageFileList.length) {
                      //图上传完成
                      List<ErpOddNumbersDatasDetail> data = [];
                      for (int i = 0;
                          i < Provider.of<ErpInfo>(context).mode.details.length;
                          i++) {
                        if (Provider.of<ErpInfo>(context)
                                .mode
                                .details
                                .elementAt(i)
                                .qty !=
                            0) {
                          data.add(Provider.of<ErpInfo>(context)
                              .mode
                              .details
                              .elementAt(i));
                        }
                      }
                      List<InvListDatasImglist> img = new List();
                      for (int i = 0; i < imageList.length; i++) {
                        img.add(InvListDatasImglist(
                            imgstr: imageList.elementAt(i)));
                      }
                      InternetAPI.getInstance().post(
                        "OMS/MiAllocationTaskDetail/AddMiAllocationTaskDetail",
                        (data) {
                          print(data.toString());
                          //Navigator.popAndPushNamed(context, "/success",result: "wu");
                          if (data == true) {
                            Navigator.pop(context, "ok");
                            TostUtil.showToast("提交成功");
                          }
                        },
                        errorCallBack: (err) {
                          setState(() {
                            load = false;
                          });
                        },
                        params: {
                          "operaterUserName": DataSingleton().Data.username,
                          "operaterUserId": DataSingleton().Data.id,
                          "tenantId": DataSingleton().Data.tenantId,
                          "creationTime":
                              DateTime.now().toString().substring(0, 19),
                          "carno": proText + controller2.text,
                          "applytime": time,
                          "erpno": selectValue,
                          "driver": controller0.text,
                          "phone": controller1.text,
                          "detailList": data,
                          "orgId": orgId,
                          "projectname":
                              detailsBean.details.elementAt(0).projectname,
                          "projectno":
                              detailsBean.details.elementAt(0).projectno,
                          "supplyname":
                              detailsBean.details.elementAt(0).suppliername,
                          "imgList": img,
                          "warehouseid": DataSingleton().warehouseChoice.id,
                          "appointmentmode": "20",
                          "department": data[0].department,
                          //"department": "雄安供电公司",
                        },
                      );
                    } else {
                      TostUtil.showToast("大图上传中，请稍后");
                    }
                  }
                } else {
                  TostUtil.showToast("请选择预约时间");
                }
              } else {
                TostUtil.showToast("物资明细不能为0");
              }
            } else {
              TostUtil.showToast("请填写正确车牌");
            }
          } else {
            TostUtil.showToast("请填写车牌号");
          }
        } else {
          TostUtil.showToast("请填写司机手机号");
        }
      } else {
        TostUtil.showToast("请填写司机姓名");
      }
    } else {
      TostUtil.showToast("请输入正确的单号");
    }
  }

  _changeText(text) {
    proText = text;
  }

  void matchErpInfo(String value) {
    for (int i = 0; i < beanNew.datas.length; i++) {
      if (value == bean.datas.elementAt(i).erpno) {
        detailsBean = beanNew.datas.elementAt(i);
        Provider.of<ErpInfo>(context).setMode(bean.datas.elementAt(i));
        setState(() {
          index = i;
          visibility = false;
          selectValue = value;
        });
        return;
      }
    }
    setState(() {
      visibility = true;
      selectValue = null;
    });
    TostUtil.showToast("请输入正确的单号");
  }
}
